const jsonwebtoken = require("jsonwebtoken"); //加载包
const secretKey = "123";

function sign(payload, options = { expiresIn: 60 * 100 }) {
  try {
    const token = jsonwebtoken.sign(payload, secretKey, options);
    return token;
  } catch (error) {
    return false;
  }
}

function verify(token) {
  try {
    jsonwebtoken.verify(token, secretKey);
    return true;
  } catch (error) {
    return false;
  }
}

function jwt(ctx, next) {
  if (ctx.url === "/login") {
    if (ctx.method === "POST") {
      // 验证密码，返回token
      let postData = ctx.request.body;
      if (postData.username === "1" && postData.password === "1") {
        let token = sign({ appname: "appname" });
        ctx.type = "json";
        ctx.body = {
          meta: 200,
          token,
        };
      } else {
        ctx.type = "json";
        ctx.body = {
          meta: 400,
          msg: "用户名或密码错误",
        };
      }
    }
    return next();
  } else {
    // 验证token
    /* 从请求头中取出客户端携带的token */
    // const clientToken = ctx.headers.authorization;
    let decoded = null;
    /* 采用jwt.verify()函数的同步形式，函数返回解码后的内容 */
    try {
      decoded = verify(ctx.headers.authorization);

      if (!decoded) {
        ctx.throw(401);
      }
      next();
    } catch (err) {
      ctx.throw(401);
    }
  }
}

exports.jwt = jwt;
